import { _ as _async_to_generator } from "@swc/helpers/_/_async_to_generator";
import { _ as _object_spread } from "@swc/helpers/_/_object_spread";
import { _ as _object_spread_props } from "@swc/helpers/_/_object_spread_props";
import { _ as _to_consumable_array } from "@swc/helpers/_/_to_consumable_array";
import { _ as _ts_generator } from "@swc/helpers/_/_ts_generator";
import _Slide from "@mui/material/Slide";
import React, { useMemo, useRef } from "react";
import SecondaryLayout from "../../compoents/secondary-layout";
import ScrollView from "../../compoents/scroll-view";
import { useMount, useReactive } from "ahooks";
import classes from "./nftsHistory.module.less";
import classNames from "classnames";
import { useDispatch, useSelector } from "react-redux";
import NftTxnDetails from "./nft-txn-details";
import useRouter from "../../hooks/useRouter";
import utilsFilters from "../../utils/filters";
import { getNFTRecord } from "../../api/wallet";
import useServices from "../../hooks/useRequest";
import { formateDate } from "../../utils";
// import { utils } from "ethers";
import { matchTheme, getChainName, getMapFinalValue } from "../../utils";
import { TEST_CHAIN, isDevChain, MAIN_CHAIN } from "../../config";
import useCalculateAmount from "../../hooks/useCalculateAmount";
import { useTranslation } from "react-i18next";
import i18n, { LocalKeyMap } from "../../local";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
var DateFormatStr = {
    zh: "YYYY-MM-D",
    en: "D MMM YYYY"
};
var formatDate = function(date) {
    return formateDate(date, DateFormatStr[i18n.language]);
};
var HistoryItem = function(props) {
    var theme = useSelector(function(state) {
        return state.app.theme;
    });
    var toFormatEther = useCalculateAmount().toFormatEther;
    var t = useTranslation().t;
    // const star = useMemo(() => {
    //   if (props.type === "inGameAction" && Math.random() >= 0.5) {
    //     return (
    //       <div
    //         className={classNames(
    //           classes.star,
    //           Math.random() > 0.5 ? classes.star_s : classes.star_f
    //         )}
    //       >
    //         <img className={classes.bg} />
    //         <div className={classes.main}>+100</div>
    //         <div className={classes.unit}>BUSD</div>
    //       </div>
    //     );
    //   }
    //   return null;
    // }, [props.type]);
    var nftStatus = useMemo(function() {
        return /*#__PURE__*/ _jsxs("div", {
            className: classes.status,
            children: [
                t(LocalKeyMap.status),
                ": ",
                props.handleStatus
            ]
        });
    }, []);
    var gas = useMemo(function() {
        return /*#__PURE__*/ _jsxs("div", {
            className: classes.gas,
            children: [
                t(LocalKeyMap.transferFee),
                ":",
                " ",
                "".concat(toFormatEther(props.gas || "0", {
                    contract: "n/a",
                    chainType: props.chainType
                }))// ETHEREUM.includes(props.chainType) ? 'ETH' : 'BNB'
                .concat(getMapFinalValue([
                    getChainName(props.chainType)
                ], {
                    BSC: "BNB",
                    ETHEREUM: "ETH",
                    CONFLUX: "CFX"
                }))
            ]
        });
    }, [
        props.gas,
        props.tokenId
    ]);
    var inGame = useMemo(function() {
        return /*#__PURE__*/ _jsx("div", {
            className: classNames(classes.internal, classes.tag),
            children: t(LocalKeyMap["nftHistory.tag.game"])
        });
    }, []);
    var internal = useMemo(function() {
        return /*#__PURE__*/ _jsx("div", {
            className: classNames(classes.internal, classes.tag),
            children: t(LocalKeyMap["nftHistory.tag.internal"])
        });
    }, []);
    return /*#__PURE__*/ _jsxs("div", {
        className: classes.history_item,
        onClick: props.onClick,
        children: [
            /*#__PURE__*/ _jsxs("div", {
                className: classes.info,
                children: [
                    /*#__PURE__*/ _jsx("div", {
                        className: classes.img,
                        children: /*#__PURE__*/ _jsx("img", {
                            // src={getNftImgSrc(props.tokenId, {
                            //   chainType: props.chainType,
                            //   contract: props.contract,
                            // })}
                            src: props.logoUrl
                        })
                    }),
                    /*#__PURE__*/ _jsxs("div", {
                        className: classes.detail,
                        children: [
                            /*#__PURE__*/ _jsx("div", {
                                className: classes.name,
                                children: props.name
                            }),
                            /*#__PURE__*/ _jsxs("div", {
                                className: classes.tag_list,
                                children: [
                                    /*#__PURE__*/ _jsx("div", {
                                        className: classNames(classes.type, classes.tag),
                                        children: props.type == "in" ? t(LocalKeyMap["nftHistory.tag.in"]) : t(LocalKeyMap["nftHistory.tag.to"]) || "-"
                                    }),
                                    props.handleType == "INTERNAL" ? internal : props.handleType == "IN_GAME" ? inGame : null
                                ]
                            }),
                            /*#__PURE__*/ _jsx("div", {
                                className: classes.origin,
                                children: props.type == "in" ? "".concat(t(LocalKeyMap.from), " ").concat(utilsFilters.stringMethod(props.from || "")) : "".concat(t(LocalKeyMap["sendToken.to"]), " ").concat(utilsFilters.stringMethod(props.to || ""))
                            }),
                            props.handleType != "IN_GAME" && gas,
                            props.handleType == "IN_GAME" ? nftStatus : null
                        ]
                    })
                ]
            }),
            /*#__PURE__*/ _jsx("div", {
                className: classes.icon,
                children: /*#__PURE__*/ _jsxs("div", {
                    className: classes.label,
                    children: [
                        /*#__PURE__*/ _jsx("img", {
                            src: matchTheme(theme, {
                                light: require("../../assets/icons/light/label.svg"),
                                dark: require("../../assets/icons/dark/label.svg")
                            })
                        }),
                        /*#__PURE__*/ _jsx("span", {
                            className: classNames(props.status == "active" ? classes.padding : props.status == "success" ? classes.success : classes.failed),
                            children: props.status == "active" ? t(LocalKeyMap.inProcess) : props.status == "success" ? t(LocalKeyMap.confirmed) : t(LocalKeyMap.failed)
                        })
                    ]
                })
            })
        ]
    });
};
function NftsHistory() {
    var _state_select;
    var state = useReactive({
        data: {},
        page: 1,
        total: 0,
        maxPage: 1,
        // size: 30,
        size: 1000,
        select: null,
        selectIndex: null
    });
    var _useRouter = useRouter(), query = _useRouter.location.query;
    var services = useServices({
        getNFTRecord: getNFTRecord,
        getAllNFTRecord: function() {
            var _ref = _async_to_generator(function(params) {
                return _ts_generator(this, function(_state) {
                    return [
                        2,
                        Promise.all([
                            getNFTRecord(_object_spread_props(_object_spread({}, params), {
                                chainType: "bnb"
                            })),
                            getNFTRecord(_object_spread_props(_object_spread({}, params), {
                                chainType: "ethereum"
                            }))
                        ])
                    ];
                });
            });
            return function(params) {
                return _ref.apply(this, arguments);
            };
        }()
    });
    var t = useTranslation().t;
    var bScroll = useRef();
    var dispatch = useDispatch();
    var fetchData = function() {
        var _ref = _async_to_generator(function() {
            var originData, id, currentItem, realData, err;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        _state.trys.push([
                            0,
                            2,
                            ,
                            3
                        ]);
                        return [
                            4,
                            services.getNFTRecord({
                                pageNum: state.page,
                                pageSize: state.size,
                                chainType: window.CHAIN_TYPE || (isDevChain ? TEST_CHAIN : MAIN_CHAIN)
                            })
                        ];
                    case 1:
                        originData = _state.sent();
                        if (originData.code != 200) return [
                            2
                        ];
                        if ((query === null || query === void 0 ? void 0 : query.from) === "goDetail") {
                            id = query === null || query === void 0 ? void 0 : query.detailId;
                            currentItem = originData.data.list.find(function(item) {
                                return item.id == id;
                            });
                            state.select = currentItem;
                        }
                        state.total = originData.data.total;
                        state.maxPage = Math.ceil(state.total / state.size);
                        realData = _to_consumable_array(originData.data.list).reduce(function(next, prev) {
                            /** 按时间进行分类 */ var date = formatDate(prev.transferTime);
                            if (next[date]) {
                                next[date].push(prev);
                            } else {
                                next[date] = [
                                    prev
                                ];
                            }
                            return next;
                        }, {});
                        state.data = realData;
                        return [
                            3,
                            3
                        ];
                    case 2:
                        err = _state.sent();
                        console.log(err);
                        return [
                            3,
                            3
                        ];
                    case 3:
                        return [
                            2
                        ];
                }
            });
        });
        return function fetchData() {
            return _ref.apply(this, arguments);
        };
    }();
    var fetchNextPage = function() {
        var _ref = _async_to_generator(function(page) {
            var nextData, nextRealData, err;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        _state.trys.push([
                            0,
                            2,
                            ,
                            3
                        ]);
                        return [
                            4,
                            services.getNFTRecord({
                                pageNum: page,
                                pageSize: state.size,
                                chainType: window.CHAIN_TYPE || (isDevChain ? TEST_CHAIN : MAIN_CHAIN)
                            })
                        ];
                    case 1:
                        nextData = _state.sent();
                        if (nextData.code !== 200) return [
                            2
                        ];
                        nextRealData = _to_consumable_array(nextData.data.list).reduce(function(next, prev) {
                            /** 按时间进行分类 */ var date = formatDate(prev.transferTime);
                            if (next[date]) {
                                next[date].push(prev);
                            } else {
                                next[date] = [
                                    prev
                                ];
                            }
                            return next;
                        }, {});
                        Object.keys(nextRealData).forEach(function(date) {
                            if (state.data[date]) {
                                state.data[date] = _to_consumable_array(state.data[date]).concat(_to_consumable_array(nextRealData[date]));
                            } else {
                                state.data[date] = nextRealData[date];
                            }
                        });
                        return [
                            3,
                            3
                        ];
                    case 2:
                        err = _state.sent();
                        console.log(err);
                        return [
                            3,
                            3
                        ];
                    case 3:
                        return [
                            2
                        ];
                }
            });
        });
        return function fetchNextPage(page) {
            return _ref.apply(this, arguments);
        };
    }();
    var changeSelectStatus = function(newDetail) {
        if (state.selectIndex) {
            state.data[state.selectIndex.date][state.selectIndex.index] = newDetail;
        }
    };
    useMount(fetchData);
    return /*#__PURE__*/ _jsxs(_Fragment, {
        children: [
            /*#__PURE__*/ _jsx(SecondaryLayout, {
                className: classNames(classes.nfts_history, state.select ? classes.v_h : ""),
                title: /*#__PURE__*/ _jsx("span", {
                    className: classes.main_title,
                    children: t(LocalKeyMap["nftHistory.title"])
                }),
                backFn: function() {
                    var queryBack = (query === null || query === void 0 ? void 0 : query.from) ? {
                        currentType: query === null || query === void 0 ? void 0 : query.from
                    } : undefined;
                    dispatch.app.BACK(queryBack);
                },
                children: /*#__PURE__*/ _jsx(ScrollView, {
                    className: classes.view_port,
                    scrollY: true,
                    renderPullUpTip: function(s, defaultDom) {
                        if (s == "succeed") {
                            return null;
                        }
                        return defaultDom;
                    },
                    pullUpLoad: {
                        threshold: 0
                    },
                    onPullingUp: /*#__PURE__*/ _async_to_generator(function() {
                        return _ts_generator(this, function(_state) {
                            // return new Promise((resolve) => {
                            //   setTimeout(() => {
                            //     resolve("");
                            //   }, 3000);
                            // });
                            // console.log('test',bScroll.current)
                            /** 暂时有问题不触底 */ if (state.page >= state.maxPage) {
                                /** 关闭 */ // bScroll.current?.closePullUp();
                                return [
                                    2
                                ];
                            }
                            state.page = state.page + 1;
                            return [
                                2,
                                new Promise(function(resolve) {
                                    /** 是否有下一页 */ var hasNext = state.page < state.maxPage;
                                    fetchNextPage(state.page).finally(function() {
                                        return resolve(hasNext);
                                    });
                                })
                            ];
                        });
                    }),
                    children: Object.keys(state.data).length ? /*#__PURE__*/ _jsx("div", {
                        children: Object.keys(state.data).map(function(type) {
                            var _category_map;
                            var category = state.data[type];
                            return /*#__PURE__*/ _jsxs("div", {
                                className: classes.class,
                                children: [
                                    /*#__PURE__*/ _jsx("div", {
                                        className: classes.title,
                                        children: type
                                    }),
                                    /*#__PURE__*/ _jsx("div", {
                                        className: classes.body,
                                        children: (_category_map = category.map) === null || _category_map === void 0 ? void 0 : _category_map.call(category, function(item, i) {
                                            return /*#__PURE__*/ _jsx(HistoryItem, _object_spread({
                                                onClick: function() {
                                                    state.select = item;
                                                    state.selectIndex = {
                                                        date: type,
                                                        index: i
                                                    };
                                                }
                                            }, item), item.id);
                                        })
                                    })
                                ]
                            }, type);
                        })
                    }) : /*#__PURE__*/ _jsx("div", {
                        className: classes.empty,
                        children: /*#__PURE__*/ _jsxs("span", {
                            children: [
                                " ",
                                t(LocalKeyMap["nftHistory.empty"])
                            ]
                        })
                    })
                })
            }),
            /*#__PURE__*/ _jsx(_Slide, {
                in: !!state.select,
                direction: "left",
                unmountOnExit: true,
                children: /*#__PURE__*/ _jsx(NftTxnDetails, _object_spread_props(_object_spread({
                    backFn: function() {
                        if ((query === null || query === void 0 ? void 0 : query.from) === "goDetail") {
                            dispatch.app.BACK();
                        } else {
                            state.select = null;
                            state.selectIndex = null;
                        }
                    },
                    id: (_state_select = state.select) === null || _state_select === void 0 ? void 0 : _state_select.id
                }, state.select), {
                    className: classes.trading_details_layout,
                    handlerChangeStatus: changeSelectStatus
                }))
            })
        ]
    });
}
export default NftsHistory;

 //# sourceMappingURL=index.js.map